<template>
   <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 警示框 -->
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon >
            </el-alert>
            <!-- 分类参数展示区域 -->
            <el-row>
                <el-col class="cat">
                    <span>选择商品分类：</span>
                    <!-- 级联选择框 -->
                    <el-cascader  v-model="selectKeys" :options="cateList" :props="cateProps" @change="handleChange">
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tab栏选择区域 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 添加动态参数区域 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="btnDisabled" @click="addDialogVisible = true">添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe>
                    <!-- 展开行 -->
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag :key = "i" v-for="(item,i) in scope.row.attr_vals" closable @close="removeAttr(scope.row,i)">
                                {{item}}
                            </el-tag>
                            <!-- 输入框 -->
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                            </el-input>
                            <!-- 添加按钮 -->
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteAttr(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 添加静态属性区域 -->
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="btnDisabled" @click="addDialogVisible = true">添加属性</el-button>
                    <!-- 静态属性表格 -->
                    <el-table :data="onlyTableData" border stripe>
                        <!-- 属性展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag :key = "i" v-for="(item,i) in scope.row.attr_vals" closable @close="removeAttr(scope.row,i)">
                                    {{item}}
                                </el-tag>
                                <!-- 输入框 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <!-- 添加按钮 -->
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteAttr(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加参数对话框 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 添加表单 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改参数或属性对话框 -->
        <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <!-- 修改表单 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
   </div>
</template>

<script>
export default {
  // 数据
  data () {
    return {
      // 选择框选项数据
      cateList: [],
      // 级联选择框配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择框选中的数据数组
      selectKeys: [],
      // tab栏
      activeName: 'many',
      // 用来保存动态参数数据
      manyTableData: [],
      // 用来保存静态属性数据
      onlyTableData: [],
      // 控制添加参数对话框的显示或隐藏
      addDialogVisible: false,
      // 添加参数的表单数据对象
      addForm: {
        attr_name: ''
      },
      // 添加表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      // 控制修改参数.属性对话框的显示或隐藏
      editDialogVisible: false,
      // 修改参数.属性对话框中的表单
      editForm: {
        attr_name: ''
      },
      // 修改表单的验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      }
    }
  },
  // 加载数据阶段
  created () {
    // 获取商品分类数据
    this.getCateList()
  },
  // 方法
  methods: {
    // 获取商品分类数据方法
    async getCateList () {
      const { data: res } = await this.$axios.get('categories')
      // 如果数据获取失败
      if (res.meta.status !== 200) return this.$message.error('获取参数数据失败')
      //    获取成功
      this.cateList = res.data
    },
    // 用级联选择的参数获取数据
    async handleChange () {
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表数据失败')
      };
      // 参数的属性字符串转为数组，遍历生成tag
      res.data.forEach(element => {
        element.attr_vals = element.attr_vals ? element.attr_vals.split(',') : []
        // 每一项添加一个属性，添加一个bool值控制文本框的显示或者隐藏
        element.inputVisible = false
        // 每一项添加一个属性，添加一个inputValue保存文本框值
        element.inputValue = ''
      })
      if (this.activeName === 'many') {
        // 获取的是动态参数
        this.manyTableData = res.data
      } else if (this.activeName === 'only') {
        // 获取的是静态属性
        this.onlyTableData = res.data
      };
    },
    // tab栏切换触发函数
    handleTabClick () {
      this.handleChange()
    },
    // 添加属性
    addParams () {
      // 添加属性校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName,
          attr_vals: 'a,b,c'
        })
        if (res.meta.status !== 201) {
          return this.$message.error('添加' + this.titleText + '数据失败')
        };
        this.$message.success('添加属性成功')
        this.addDialogVisible = false
        this.handleChange()
      })
    },
    // 监听添加属性对话框关闭事件
    addDialogClosed () {
      // 重置输入框
      this.$refs.addFormRef.resetFields()
    },
    // 编辑修改对话框 获取编辑参数
    async showEditDialog (id) {
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes/${id}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数数据失败')
      };
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改，编辑参数
    editParams () {
      // 先表单验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName,
          attr_vals: this.editForm.attr_vals
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数数据失败')
        };
        this.$message.success('修改参数数据成功')
        this.editDialogVisible = false
        this.handleChange()
      })
    },
    // 编辑对话框关闭
    editDialogClosed () {
      // 重置表单
      this.$refs.editFormRef.resetFields()
    },
    // 删除参数属性
    async deleteAttr (id) {
      const right = await this.$confirm('请问是否要删除该' + this.titleText, '删除提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => { err })
      if (right !== 'confirm') {
        return this.$message.info('已经取消删除')
      };
      const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数数据失败')
      };
      this.$message.success('删除' + this.titleText + '数据成功')
      this.handleChange()
    },

    // 添加动态和静态参数的扩展属性
    async handleInputConfirm (row) {
      // 判断tag输入框输入的值
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      };
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      this.saveAttrVals(row)
    },
    // 展示输入框，自动获取焦点
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        // 让文本框自动获得焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除属性
    removeAttr (row, i) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 定义保存属性的函数
    async saveAttrVals (row) {
      const { data: res } = await this.$axios.put('categories/' + row.cat_id + '/attributes/' + row.attr_id, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('添加参数失败')
      this.$message.success('添加参数成功')
      row.inputVisible = false
      this.handleChange()
    }
  },
  // 计算属性
  computed: {
    // 该函数返回布尔值控制按钮禁用状态
    btnDisabled () {
      // 判断级联选择框是否选择三层分类选项
      if (this.selectKeys.length !== 3) {
        return true
      };
      return false
    },
    // 获取级联选择框选中的三级分类id
    cateId () {
      // 选择了三层分类，返回第三个分类id
      if (this.selectKeys.length === 3) {
        return this.selectKeys[this.selectKeys.length - 1]
      }
      return null
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else if (this.activeName === 'only') {
        return '静态属性'
      };
      return null
    }
  }
}
</script>

<style lang="less" scoped>
    .cat{
        margin:15px 0 15px 0 ;
    }
    .el-tag{
        margin:0px 15px 10px 0 ;
    }
    .input-new-tag{
        width: 200px;
    }
</style>
